package com.xinshujia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinshujia.dao.RoleDao;
import com.xinshujia.dao.UserDao;
import com.xinshujia.entity.UserEntity;
import com.xinshujia.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-15 19:36       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    private final UserDao userDao;
    private final RoleDao roleDao;

    public UserServiceImpl(UserDao userDao, RoleDao roleDao) {
        this.userDao = userDao;
        this.roleDao = roleDao;
    }

    /*新增用户*/
    @Override
    public boolean insert(UserEntity userEntity) {
        userEntity.setAccountNonExpired(false);
        userEntity.setAccountNonLocked(false);
        userEntity.setCredentialsNonExpired(false);
        userEntity.setEnabled(true);
        int count = userDao.insert(userEntity);
        return count > 0;
    }

    /*根据Id删除用户（实际是更新操作）*/
    @Override
    public boolean deleteById(Long id) {
        if (id != null) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(id);
            userEntity.setEnabled(false);
            int count = userDao.updateById(userEntity);
            return count > 0;
        }
        return false;
    }

    /*分页查询*/
    @Override
    public Page<UserEntity> findAllByPage(Long pageNum, Long pageSize, String username) {
        // 1. 查询条件构造器
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasLength(username)){
            queryWrapper.like("username", username)
                    .or()
                    .like("phone", username);
        }
//        queryWrapper.eq("enabled",true);
        // 2. 分页查询条件
        Page<UserEntity> page = new Page<>(pageNum,pageSize);

        // 3. 查询结果
        Page<UserEntity> selectPage = userDao.selectPage(page, queryWrapper);
        // 4. 添加用户拥有的角色
        for (UserEntity user : selectPage.getRecords()) {
            // 4.1 查询用户拥有的角色，并赋值
            user.setRoles(roleDao.getRolesByUid(user.getId()));
            // 4.2 设置用户密码为null, 不让前端获取
            user.setPassword("******");
        }
        return selectPage;
    }

    /*单个属性更新*/
    @Override
    public boolean patchUser(Long id, int enabled) {
        return userDao.patchUser(id,enabled) > 0;
    }

}
